package com.lovepick.fragment;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.lovepick.GlobalApp;
import com.lovepick.R;
import com.lovepick.adapter.MyOrderAdapter;
import com.lovepick.bean.Order;
import com.lovepick.http.HttpThread;
import com.lovepick.util.BaseUtils;
import com.lovepick.util.Constant;
import com.lovepick.util.IRecmdListener;
import com.lovepick.util.OrderOperation;
import com.lovepick.util.OrderState;

public class ManageFragment extends Fragment
{
	private static final String TAG = "ManageFragment";
	private ManageHandler mHandler;
	private String mRole;

	private static OrderOperation mOperation = OrderOperation.MANAGE;
	private List<Order> mOrders = null;
	private MyOrderAdapter mAdapter = null;
	private HttpThread mThread;
	private Order mSelectedOrder = null;

	private ListView mManageView;
	private ProgressBar mBar;
	private RadioGroup mRolesGroup;
	private RadioButton mPassengerRadioButton;
	private RadioButton mDriverRadioButton;
	private IRecmdListener mRecmdListener;
	private OrderOperationListener mOrderListener;

	/**
	 * @author Liutong
	 *
	 * <h1>订单管理相关的一些接口</h1>
	 *
	 */
	public interface OrderOperationListener
	{
		/**
		 * 乘客在订单管理点击某条已完成订单时查看订单详情
		 * </br>
		 * 详情包括接受订单的司机, 交易币值及座位数
		 *
		 * @param result 从服务器返回的该条订单的详情
		 */
		public void onShowInfosForPassenger(String result);

		/**
		 * 司机在订单管理页面查看申请订单的乘客列表
		 * </br>
		 * 订单状态可能为待处理或者新申请
		 *
		 * @param result 从服务器返回的申请了该订单的乘客列表
		 * @param order	当前选中的司机订单信息
		 */
		public void onShowInfosForDriver(String result, Order order);
	}

	@Override
    public void onAttach(Activity activity)
	{
		super.onAttach(activity);

		// 确保包含了本Fragment的Activity实现了相关回调接口, 否则抛出异常.
		try
		{
			mRecmdListener = (IRecmdListener) activity;
		}
		catch (ClassCastException e)
		{
			throw new ClassCastException(activity.toString()
					+ " must implement IRecmdListener");
		}

		try
		{
			mOrderListener = (OrderOperationListener) activity;
		}
		catch (ClassCastException e)
		{
			throw new ClassCastException(activity.toString()
					+ " must implement OrderOperationListener");
		}

    }

	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);
		mRole = GlobalApp.getInstance().getRole();
		if (null == mRole)
		{
			mRole = Constant.PASSENGER;
		}

		mManageView = (ListView) getActivity().findViewById(R.id.lv_order_manage);
		mBar = (ProgressBar) getActivity().findViewById(R.id.progBar_manage);
		mRolesGroup = (RadioGroup) getView().findViewById(R.id.rg_roles);
		mPassengerRadioButton = (RadioButton) getActivity().findViewById(R.id.radio_passenger);
		mDriverRadioButton = (RadioButton) getActivity().findViewById(R.id.radio_driver);

		mRolesGroup.setOnCheckedChangeListener(mChangeListener);
		mManageView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
		mManageView.setMultiChoiceModeListener(mListener);
		mHandler = new ManageHandler(this);
		registerForContextMenu(mManageView);
		if (mRole.equals(Constant.PASSENGER))
		{
			mPassengerRadioButton.setChecked(true);
		}
		else
		{
			mDriverRadioButton.setChecked(true);
		}
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.order_manage, container, false);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
	{
		inflater.inflate(R.menu.order_manage, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.menu_refresh_order:
				init();
				return true;

			default:
				return super.onOptionsItemSelected(item);
		}
	}

	private void init()
	{
		mOperation = OrderOperation.MANAGE;
		String url = Constant.HTTP_URL_ORDER_MANAGE + "/" + mRole;
		mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url, null);
		mThread.start();
		mBar.setVisibility(View.VISIBLE);
	}

	private void deleteOrder(int orderID)
	{
		Log.i(TAG, "---删除订单---");
		mOperation = OrderOperation.DELETE;
		String url = Constant.HTTP_URL_ORDER_DELETE + orderID + "/" + mRole;
		mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url, null);
		mThread.start();
		mBar.setVisibility(View.VISIBLE);
	}

	private void getOrderDetail(int orderID)
	{
		Log.i(TAG, "---获取订单详情---");
		mOperation = OrderOperation.DETAIL;
		String url = Constant.HTTP_URL_ORDER_DETAIL  + "/" + mRole + "/" + orderID;
		mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url, null);
		mThread.start();
		mBar.setVisibility(View.VISIBLE);
	}

	private void recmdOrders(Order order)
	{
		Log.i(TAG, "---推荐订单---");
		mOperation = OrderOperation.RECOMMEND;
		String url = "";
		url += "?test=test";
		url += "&slat=" + order.getSlat();
		url += "&slng=" + order.getSlng();
		url += "&dlat=" + order.getDlat();
		url += "&dlng=" + order.getDlng();
		url += "&goTime=" + order.getGoTime();
		url += "&offset=" + order.getOffset();

		try
		{
			url = java.net.URLEncoder.encode(url, "UTF-8");
			url = Constant.HTTP_URL_ORDER_RECOMMED + mRole + url;
			mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url, null);
			mThread.start();
			mBar.setVisibility(View.VISIBLE);
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			BaseUtils.showToast(getActivity(), "暂时无法推荐!");
		}
	}

	private void getOrderInfo(String role, int orderID)
	{
		mOperation = OrderOperation.INFOS;
		String url;
		if (role.equals(Constant.PASSENGER))
		{
			Log.i(TAG, "---获取已完成订单信息---");
			url = Constant.HTTP_URL_ORDER_MORE_INFO + orderID;
		}
		else
		{
			Log.i(TAG, "---获取申请乘客列表信息---");
			url = Constant.HTTP_URL_ORDER_APPLY_INFOS + "/" + orderID;
		}

		mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url, null);
		mThread.start();
		mBar.setVisibility(View.VISIBLE);
	}

	private RadioGroup.OnCheckedChangeListener mChangeListener = new RadioGroup.OnCheckedChangeListener()
	{

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId)
		{
			// TODO Auto-generated method stub
			switch (checkedId)
			{
				case R.id.radio_passenger:
					mRole = Constant.PASSENGER;
					break;

				case R.id.radio_driver:
					mRole = Constant.DRIVER;
					break;

				default:
					break;
			}

			GlobalApp.getInstance().saveRole(mRole);
			init();

		}
	};

	private AbsListView.MultiChoiceModeListener mListener = new MultiChoiceModeListener()
	{
		private View mMultiSelectActionBarView;
        private TextView mSelectedConvCount;

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu)
		{
			// TODO Auto-generated method stub
			if (mMultiSelectActionBarView == null)
			{
				mMultiSelectActionBarView = LayoutInflater.from(getActivity())
						.inflate(R.layout.manage_multi_select_actionbar,
								null);

				mSelectedConvCount = (TextView) mMultiSelectActionBarView
						.findViewById(R.id.selected_conv_count);
			}
			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode)
		{
			// TODO Auto-generated method stub
			mAdapter.uncheckAll();
		}

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu)
		{
			// TODO Auto-generated method stub
			MenuInflater inflater = mode.getMenuInflater();
	        inflater.inflate(R.menu.context_manage, menu);

	        if (mMultiSelectActionBarView == null) {
                mMultiSelectActionBarView = LayoutInflater.from(getActivity())
                    .inflate(R.layout.manage_multi_select_actionbar, null);

                mSelectedConvCount =
                    (TextView)mMultiSelectActionBarView.findViewById(R.id.selected_conv_count);
            }
            mode.setCustomView(mMultiSelectActionBarView);
            ((TextView)mMultiSelectActionBarView.findViewById(R.id.title))
                .setText(R.string.select_orders);
	        return true;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item)
		{
			// TODO Auto-generated method stub
			switch (item.getItemId())
			{
				case R.id.menu_delete:
					Log.i(TAG, "## delete ##");
					deleteOrder(mSelectedOrder.getOrderID());
					mode.finish();
					return true;

				case R.id.menu_details:
					Log.i(TAG, "## details ##");
					getOrderInfo(mRole, mSelectedOrder.getOrderID());
					mode.finish();
					return true;

				case R.id.menu_recmd:
					Log.i(TAG, "## recmd ##");
					getOrderDetail(mSelectedOrder.getOrderID());
					//recmdOrders(mSelectedOrder);
					mode.finish();
					return true;

				default:
					return false;
			}

		}

		@Override
		public void onItemCheckedStateChanged(ActionMode mode, int position,
				long id, boolean checked)
		{
			// TODO Auto-generated method stub
			Menu menu = mode.getMenu();
			Order order = mOrders.get(position);
			mSelectedOrder = order;
			if (order.getState().equals(OrderState.FINISHED))
			{
				menu.findItem(R.id.menu_delete).setVisible(false);
				menu.findItem(R.id.menu_recmd).setVisible(false);
				menu.findItem(R.id.menu_details).setVisible(true);
			}
			else if (order.getState().equals(OrderState.TO_DEAL))
			{
				menu.findItem(R.id.menu_delete).setVisible(true);
				if (mRole.equals(Constant.PASSENGER))
				{
					menu.findItem(R.id.menu_details).setVisible(false);
				}
				else
				{
					menu.findItem(R.id.menu_details).setVisible(true);
				}

				menu.findItem(R.id.menu_recmd).setVisible(true);

			}
			else
			{
				menu.findItem(R.id.menu_delete).setVisible(true);
				menu.findItem(R.id.menu_details).setVisible(true);
			}

			if (mManageView.getCheckedItemCount() > 1)
			{
				menu.findItem(R.id.menu_details).setVisible(false);
				menu.findItem(R.id.menu_recmd).setVisible(false);
			}

			mOrders.get(position).setChecked(checked);
			mAdapter.notifyDataSetChanged();
			final int checkedCount = mManageView.getCheckedItemCount();
			mSelectedConvCount.setText(Integer.toString(checkedCount));
		}
	};

	@Override
	public void onPause()
	{
		super.onPause();
		unregisterForContextMenu(mManageView);
		GlobalApp.getInstance().saveRole(mRole);
	}

	public void refresh(String result)
	{
		mOrders = BaseUtils.getOrdersSimple(result);
		if (null == mOrders)
		{
			BaseUtils.showToast(getActivity(), R.string.order_manage_none);
		}
		else
		{
			mAdapter = new MyOrderAdapter(getActivity(), mOrders);
			mManageView.setAdapter(mAdapter);
		}

	}

	private static class ManageHandler extends Handler
	{
		private WeakReference<ManageFragment> mReference;
		private ManageFragment mFragment;
		private String result;

		public ManageHandler(ManageFragment fragment)
		{
			mReference = new WeakReference<ManageFragment>(fragment);
		}

		@Override
		public void handleMessage(Message msg)
		{
			mFragment = mReference.get();
			switch (msg.what)
			{
				case Constant.MSG_HTTP_SUCCESS:
					result = msg.getData().getString(Constant.HTTP_RESULT);
					result = result.replace("\\\"", "\"")		// \" --> "
							.replace("\"[", "[")				// "[ --> [
							.replace("]\"", "]")				// ]" --> ]
							.replace("\"points\":\"\"", "\"points\":[]");	// "points":""
																			// -->
																			// "points:":[]
					Log.i(TAG, result);
					mFragment.mBar.setVisibility(View.GONE);
					switch (mOperation)
					{
						// 订单管理
						case MANAGE:
							if (result.startsWith(Constant.JSON_ARRAY_START))
							{
								Log.i(TAG, "## get order mange infos ##");
								mFragment.mOrders = BaseUtils.getOrdersSimple(result);
								if (null == mFragment.mOrders)
								{
									BaseUtils.showToast(
											mFragment.getActivity(),
											R.string.order_manage_none);
								}
								else
								{
									mFragment.mAdapter = new MyOrderAdapter(
											mFragment.getActivity(),
											mFragment.mOrders);
									mFragment.mManageView
											.setAdapter(mFragment.mAdapter);
								}
							}
							else
							{
								BaseUtils.showToast(mFragment.getActivity(),
										R.string.order_manage_none);
								if (mFragment.mAdapter != null)
								{
									mFragment.mAdapter = null;
									mFragment.mOrders.clear();
								}
							}
							break;

						// 获取订单详细信息
						case DETAIL:
							if (!TextUtils.isEmpty(result))
							{
								Log.i(TAG, "## get order detail ##");
								mFragment.mSelectedOrder = BaseUtils.getOrderDetail(result);
								if (null == mFragment.mSelectedOrder)
								{
									BaseUtils.showToast(mFragment.getActivity(),
											R.string.order_detail_fail);
								}
								else
								{
									mFragment.recmdOrders(mFragment.mSelectedOrder);
								}
							}
							else
							{
								BaseUtils.showToast(mFragment.getActivity(),
										R.string.order_detail_fail);
							}
							break;

						// 删除订单
						case DELETE:
							if (result.equals(Constant.HTTP_ORDER_DELETE_SUCCESS))
							{
								BaseUtils.showToast(mFragment.getActivity(),
										R.string.order_delete_success);
								mFragment.mAdapter
										.removeItem(mFragment.mSelectedOrder);
							}
							else
							{
								BaseUtils.showToast(mFragment.getActivity(),
										R.string.order_delete_fail);
							}
							break;

						case INFOS:
							// 对于司机, 查看乘客的拼车申请;
							// 对于乘客, 查看完成的订单信息.
							if (result.startsWith(Constant.JSON_ARRAY_START))
							{
								if (mFragment.mRole.equals(Constant.PASSENGER))
								{
									mFragment.mOrderListener.onShowInfosForPassenger(result);
								}
								else
								{
									mFragment.mOrderListener.onShowInfosForDriver(result,
											mFragment.mSelectedOrder);
								}

							}
							else if (result.equals(Constant.JSON_ARRAY_EMPTY)) {
								BaseUtils.showToast(mFragment.getActivity(), R.string.order_info_empty);
							}
							else
							{
								BaseUtils.showToast(mFragment.getActivity(), R.string.order_info_fail);
							}
							break;

						case RECOMMEND:
							// 推荐订单
							if (result.startsWith(Constant.JSON_ARRAY_START))
							{
								mFragment.mRecmdListener.onGetRecmd(mFragment.mRole, false, result);
								mFragment
										.unregisterForContextMenu(mFragment.mManageView);
								GlobalApp.getInstance().saveCurrentOrder(
										mFragment.mSelectedOrder);
							}
							else
							{
								BaseUtils.showToast(mFragment.getActivity(),
										R.string.get_recmd_fail);
							}

							break;

						default:
							mFragment.mBar.setVisibility(View.GONE);
							break;
					}
					break;

				case Constant.MSG_HTTP_ERROR:
					mFragment.mBar.setVisibility(View.GONE);
					BaseUtils.showToast(mFragment.getActivity(), R.string.network_connnect_fail);
					break;

				default:
					mFragment.mBar.setVisibility(View.GONE);
					BaseUtils.showToast(mFragment.getActivity(), R.string.network_connnect_fail);
					break;
			}
		}
	}
}
